/******************************************************************************************************
Copyright (C) 2017 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, BaseConverter, NMRSpectrum, File, Str, TextStream, settings, strings, Env, Dir, mainWindow*/
/*jslint plusplus: true, indent: 4*/

/** Default constructor of the converter
 * Defines the file filter
*/
function PeakListConverter() {
	"use strict";
	BaseConverter.call(this);
	this.exportFileFilter = "NMR 1D Peak List (*.csv *.txt)";
}

PeakListConverter.prototype = new BaseConverter();

PeakListConverter.prototype.wantsExport = function (aPageItems) {
	"use strict";
	var i, spec;

	for (i = 0; i < aPageItems.length; i++) {
		if (aPageItems[i].name === "NMR Spectrum") {
			spec = new NMRSpectrum(aPageItems[i]);
			if (spec.isValid() && spec.dimCount === 1 && spec.peaks().count) {
				return true;
			}
		}
	}
	return false;
};

PeakListConverter.prototype.exportItems = function (aPageItems, aFilename) {
	"use strict";
	var dlg, format, formats, decimals, strm, i, j, s, spec, peaks, peak, file, oldCurSpecIndex, mapObj, flagExit;

	try {

		flagExit = false;
		decimals = settings.value("PeakListConverter/DecimalsPlaces", 6);
		format = settings.value("PeakListConverter/CurrentFormat", "{ppm}{tab}{intensity}");

		if (!Env.converterUseDefaultSettings) {
			dlg = Application.loadUiFile("ricares:WPeakListConverter.ui");
			dlg.widgets.sbDecimalPlaces.value = decimals;
			dlg.widgets.cmbFormat.items = settings.value("PeakListConverter/Formats", ["{ppm}{tab}{intensity}", "{ppm}{tab}{intensity}{tab}{area}", "{ppm}{tab}{area}", "{ppm}{tab}{intensity}{tab}{width}{tab}{area}"]).map(function (aItem) {return aItem.replace(/\[/g, "{").replace(/\]/g, "}"); });
			dlg.widgets.cmbFormat.currentText = format;

			mainWindow.restoreCursor();
			if (!dlg.exec()) {
				flagExit = true;
			}

			format = dlg.widgets.cmbFormat.currentText;
			decimals = dlg.widgets.sbDecimalPlaces.value;
			formats = dlg.widgets.cmbFormat.items.filter(function (aElement, aIndex) {return aElement !== format && aIndex <= 8; });
			formats.unshift(format);
			settings.setValue("PeakListConverter/Formats", formats);
		}

		if (!flagExit) {

			settings.setValue("PeakListConverter/CurrentFormat", format);
			settings.setValue("PeakListConverter/DecimalsPlaces", decimals);

			format = format.replace(/\{tab\}/g, "\t");
			mapObj = {};

			file = new File(aFilename);
			if (file.open(File.WriteOnly)) {
				strm = new TextStream(file);
				strm.precision = decimals;
				for (i = 0; i < aPageItems.length; i++) {
					spec = new NMRSpectrum(aPageItems[i]);
					if (spec.isValid() && spec.dimCount === 1) {
						oldCurSpecIndex = spec.curSpecIndex;
						for (s = 0; s < spec.specCount; s++) {
							spec.curSpecIndex = s;
							strm.write(s + 1, '\t', Str.linifyAndQuote(spec.title));
							peaks = spec.peaks();
							peaks.sort(false);
							for (j = 0; j < peaks.count; j++) {
								peak = peaks.at(j);
								mapObj.ppm = peak.delta().toFixed(decimals);
								mapObj.intensity = peak.intensity.toFixed(decimals);
								mapObj.area = peak.integralInPts(spec).toFixed(decimals);
								mapObj.width = spec.unitsToUnits("ppm", "hz", peak.width(), 1).toFixed(decimals);
								strm.write("\t" + format.formatMap(mapObj));
							}
							strm.writeln();
						}
						spec.curSpecIndex = oldCurSpecIndex;
					}
				}
			}
		}
	} finally {
		if (!flagExit) {
			file.close();
		}
	}

	return 0;

};

Env.Converters.push(new PeakListConverter());

PeakListConverter.PeakListConverterTest = function () {
	"use strict";
	var retVal = -1,
		cnv = new PeakListConverter(),
		pageItems = mainWindow.activeDocument.selection();

	if (cnv.wantsExport(pageItems)) {
		retVal = cnv.exportItems(pageItems, Dir.home() + "/PeakList.txt");
	}
	return retVal;
};
